package com.authorization.config;

import com.alibaba.fastjson.JSONObject;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author chengyadong
 * @date 2023/11/30 10:06
 * @description 自定义身份验证异常收集，比如未登录时捕获异常抛给前端，避免重定向到springSecurity自带的登录页面
 */
public class AuthenticationEntryPointCustomer implements AuthenticationEntryPoint {
	@Override
	public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
		Throwable cause = authException.getCause();
		//资源未授权
		writerMsg(response, 2, "尚未登陆，请先登录:="+authException.getMessage());
	}

	private void writerMsg(HttpServletResponse response, Integer code, String msg) throws IOException {
		Map date = new HashMap();
		date.put("code", code);
		date.put("msg", msg);
		response.setContentType("application/json;charset=utf-8");
		PrintWriter out = response.getWriter();
		out.write(JSONObject.toJSON(date).toString());
		out.flush();
		out.close();
	}
}
